<?php
declare (strict_types=1);

namespace app\serviceapp;

use app\model\BaseModel;
use app\model\FenggeParam;
use app\model\FenggeScore;
use app\model\Personal;
use app\model\TLabel;
use app\model\User;
use app\model\UserDetails;
use app\MyException;
use app\traits\ServiceTrait;
use app\util\JwtUtil;
use app\service\AuthGroupService;
use app\model\ReportDic;
use think\facade\Cache;

/**
 * 管理员
 * Class AdminService
 * @package app\service
 */
class IndexService
{

    /**
     * 获取列表
     * @param $data
     */
    public static function getLists($data)
    {
        $where = '1 = 1 ';
        $condition = [];
        if (isset($data['type'])) {
            $where .= ' and type_code like :type ';
            $condition['type'] = $data['type'] . '%';
        }

        $list = ReportDic::where($where, $condition)->select();
        if ($list) return $list;
        return [];

    }

    public static function setPersonInfo($data)
    {
        $paramArr = json_decode($data['info'], true);
        $oneUserD = UserDetails::where('user_id = :user_id', ['user_id' => $data['user_id']])->find();
        $oneUser = User::where('user_id = :user_id', ['user_id' => $data['user_id']])->find();
        if (!$oneUser) {
            throw new MyException(10002);
        }
        if (!$oneUserD) {
            $oneUserD = new UserDetails();
        }

        $oneUserD->user_id = $data['user_id'];
        foreach ($paramArr as $k => $v) {
            $oneUserD->$k = $v;
        }

        $height = $oneUserD->shengao;
        $weight = $oneUserD->tizhong;

        $chima = Personal::where('shenggao1','<=', $height)
            ->where('shenggao2','>', $height)
            ->where('tizhon1','<=', $weight)
            ->where('tizhon2','>', $weight)
            ->value('chima');
        $oneUserD->chima = $chima;

        BaseModel::beginTrans();
        try {
            //添加用户详情表
            $oneUserD->save();

            //修改用户表
            $oneUser->sex = $paramArr['sex'];
            $oneUser->status = 2; //状态(0初始用户未填写资料，1资料填写中，2资料已填写)
            $oneUser->allowField(['sex','status'])->save();

            BaseModel::commitTrans();

        } catch (\Exception $e) {
            BaseModel::rollbackTrans();
            throw new MyException(10001, $e->getMessage());
        }

        return (object)[];
    }

    /**
     * 引导设置
     * @param $data
     * @return UserDetails
     */
    public static function setting($data)
    {
        $typeLable = [
            '1' => 'fengge',
            '2' => 'tixing',
            '3' => 'fuse',
            '4' => 'xijie',
        ];

        switch ($data['type']) {
            case '2':
            case '3':
            case '4':
                $field = $typeLable[$data['type']];
                static::checkParam($data['selectedParam'], 'app\model\TLabel', $field, $data['type']);
                break;
            case '1':
                $field = $typeLable[$data['type']];
                static::checkParam($data['selectedParam'], 'app\model\FenggeParam', $field, $data['type']);
                break;
        }

        $res = static::saveUserDetailInfo($field, $data);
        return $res;

    }

    /**
     * 检测参数
     * @param $param
     * @param $modelName 模型名称
     * @param $type 引导类型
     * @return bool
     */
    public static function checkParam($param, $modelName, $field, $type)
    {
        $model = new $modelName;
        $paramArr = explode(',', $param);
        if (strpos($param, ',')) {
            if ($modelName == 'app\model\TLabel') {
                $result = $model::where('label_type_id=:label_type_id',['label_type_id' => $type])->select($paramArr)->toArray();
            } else
                $result = $model::select($paramArr)->toArray();

            if (count($result) != count($paramArr)) {
                throw new MyException(10004);
            }
        } else {
            if ($modelName == 'app\model\TLabel') {
                $result = $model::where('label_type_id=:label_type_id',['label_type_id' => $type])->find($param);
            } else
                $result = $model::find($param);

            if (!$result) {
                throw new MyException(10004);
            }
        }

        //风格只能选择5个
        if ($field == 'fengge') {
            if (count($paramArr) != 5) {
                throw new MyException(10001,'请选择5个风格属性');
            }
        }

        //同种细节属性不能冲突
        $typeCode = [];
        /*if ($type == 'xijie') {
            foreach ($result as $k => $v) {
                $typeCode[] = explode('xijie_', $v['type_code'])[0];
            }

            $typeCode = array_unique($typeCode);
            if (count($typeCode) != count($result)) {
                throw new MyException(10001,'细节属性冲突');
            }
        }*/

       return true;
    }

    /**
     * 保存用户详情信息
     * @param $field
     * @param $data
     */
    public static function saveUserDetailInfo($field, $data)
    {
        $oneUserD = UserDetails::where('user_id = :user_id', ['user_id' => $data['user_id']])->find();
        $oneUser = UserService::getUserById($data['user_id']);
        if (!$oneUser) {
            throw new MyException(10002);
        }
        if (!$oneUserD) {
            $oneUserD = new UserDetails();
        }

        $oneUserD->user_id = $data['user_id'];
        $oneUserD->$field =  $data['selectedParam'];

        BaseModel::beginTrans();
        try {
            //添加用户详情表
            $oneUserD->save();

            //修改用户表
            if (User::USER_STATUS_FINISH != $oneUser->status) {
                $oneUser->status = User::USER_STATUS_FILLING;
                $oneUser->allowField(['sex','status'])->save();
            }

            //添加风格表
            if ($field == 'fengge') {
                $selectedFengge = explode(',', $data['selectedParam']);
                $fenggeInfo = FenggeParam::column('shaonv,youya,langman,ziran,gudian,xiju,shaonian,romantic,ruizhi,yiyuziran,qianwei','id');
                $score = [
                    'shaonv' => 0,
                    'youya' => 0,
                    'langman' => 0,
                    'ziran' => 0,
                    'gudian' => 0,
                    'xiju' => 0,
                    'shaonian' => 0,
                    'romantic' => 0,
                    'ruizhi' => 0,
                    'yiyuziran' => 0,
                    'qianwei' => 0,
                ];

                //计算风格得分
                foreach ($fenggeInfo as $k => $v) {
                    unset($v['id']);
                    if (in_array($k, $selectedFengge)) {
                        foreach ($v as $kk => $vv) {
                            $score[$kk] += $vv;
                        }
                    }
                }

                $fenggeScoreM = FenggeScore::where('user_id=:user_id', ['user_id' => $oneUserD->user_id])->find();
                if (empty($fenggeScoreM)) {
                    $fenggeScoreM = new FenggeScore();
                    $fenggeScoreM->user_id = $oneUserD->user_id;
                }

                foreach ($score as $k => $v) {
                    $fenggeScoreM->$k = $v;
                }
                $fenggeScoreM->save();

            }
            BaseModel::commitTrans();
        } catch (\Exception $e) {
            BaseModel::rollbackTrans();
            throw new MyException(10001, $e->getMessage());
        }

        return (object)[];
    }

    //获取用户的身材信息
    public static function getUserDetailInfo($userId)
    {
        $oneUser = UserDetails::where('user_id = :user_id', ['user_id' => $userId])
            ->field('fuse,tixing,xijie,fengge,shengao,tizhong,nianling')
            ->find()
            ->toArray();
        if (!$oneUser) {
            throw new MyException(10004);
        }

        $labelInfo = TLabel::column('code_name','id');
        foreach ($oneUser as $key => $value) {
            if (in_array($key, ['fuse','tixing','xijie','fengge'])) {
                $item = explode(',', $value);
                if (count($item) == 1) {
                    $oneUser[$key] = $labelInfo[$value];
                } else {
                    $labelName = '';
                    foreach ($item as $k => $v) {
                        if ($key == 'xijie') {
                            $labelName .= $labelInfo[$v] . '/';
                        } else
                            $labelName .= $labelInfo[$v] . '、';
                        $oneUser[$key] = $labelName;
                    }
                    $oneUser[$key] = mb_substr($oneUser[$key], 0, -1);
                }
            }
        }

        return $oneUser;
    }
}
